package com.es.config;

import cn.hutool.core.util.StrUtil;
import com.es.dto.HotelData;
import com.es.dto.HotelDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;

@ControllerAdvice
@Slf4j
public class HotelDataRequestBodyAdvice implements RequestBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.getParameterType().equals(HotelData.class);
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        return httpInputMessage;
    }

    @Override
    public Object afterBodyRead(Object obj, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        HotelData hotelData = (HotelData) obj;
        HotelDto hotelDto = hotelData.getQuery();
        if (hotelDto != null) {
            String location = hotelDto.getLocation();
            if (StrUtil.isNotBlank(location)) {
                String[] locationStr = location.split(",");
                Double lon = Double.parseDouble(locationStr[0]);
                Double lat = Double.parseDouble(locationStr[1]);
                hotelDto.setLon(lon);
                hotelDto.setLat(lat);
            }

            String distance = hotelDto.getDistance();
            if (StrUtil.isNotBlank(distance)) {
                hotelDto.setDistance(distance.split("-")[1]);
            }
        }
        return hotelData;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return null;
    }
}
